//
//  MyDriverVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/12/1.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "MyDriverVC.h"
#import "TopBackView.h"
#import "RootViewController.h"
#import "Common.h"
#import "MyDriverCell.h"
#import "AddCarDriverVC.h"
#import "WKProgressHUD.h"
#import "NullView.h"
#import "DriverModel.h"
#import <MJRefresh/MJRefresh.h>
#import "RLNetworkHelper.h"//网络判断


@interface MyDriverVC ()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,strong) NullView *nullView;
@property (nonatomic,strong) UIView *netView;

@property (nonatomic) int pageNo;
@property (nonatomic) NSInteger pageTotal;
@property (nonatomic,strong) NSMutableArray *dataArray;


@property (nonatomic,strong) UITableView *tableView;

@end

@implementation MyDriverVC

- (void)viewDidLoad {
    [super viewDidLoad];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"我的司机"];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = WhiteColor;
    
    self.dataArray = [NSMutableArray array];
    _pageNo = 1;
    
    [self initNullView];

    [self initDataSources];
    
    [self initTableView];
}

#pragma mark 没数据时网络提示页面
-(void)initNullView
{
    self.nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 45 * kHeight) andTitle:@"" andImage:[UIImage imageNamed:@"no_order"]];
    self.nullView.backgroundColor = GrayColor;
    
    Common *c = [[Common alloc]init];
    //创建无网络状态view
    self.netView = [c noInternet:@"网络连接失败，请检查网络设备" and:self action:@selector(NoNetPressBtn) andCGreck:CGRectMake(0, 0, Main_Width, Main_height-64)];
}


-(void)initDataSources
{
    self.nullView.label.text = @"暂无司机";
    
    NSString *string ;

    if (self.orderId ==nil) {
        //全部司机
        string = [NSString stringWithFormat:@"%@",sub_drivers];
    } else {
        //空闲司机
        string = [NSString stringWithFormat:@"%@",sub_freedrivers];
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@?pageNo=%d&pageSize=%@",string,self.pageNo,@"10"];
    
        [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss: YES];
        
        if (_pageNo == 1) {
            
            [self.dataArray removeAllObjects];
            
        }
    
            
        if ([responseObj[@"success"] boolValue]) {
            
            [self.hud dismiss:YES];
            
            if ([responseObj[@"data"] isEqual:[NSNull null]]) {
                
                [self.tableView addSubview:self.nullView];

            } else {
                
                self.pageTotal = [responseObj[@"data"][@"page"][@"totalPage"] integerValue];

            
            for (NSDictionary *dic in responseObj[@"data"][@"list"]) {
                [self.dataArray addObject:dic];
            }
            
                        
            if (self.dataArray.count > 0) {
                [self.nullView removeFromSuperview];
            } else {
                [self.tableView addSubview:self.nullView];
            }
            
            [self.tableView reloadData];
            }
            
        } else {
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];
            
        }
        
    
    } failed:^(NSString *errorMsg) {
        [self.hud dismiss:YES];
        NSLog(@"%@",errorMsg);
    }];

}


-(void)initTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64 - 55 * kHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.tableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = GrayColor;
    
    //mj
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];

    
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.backgroundColor = YellowColor;
    addButton.frame = CGRectMake(20, CGRectGetMaxY(self.tableView.frame) + 10 * kHeight, screenWidth - 40, 35 * kHeight);
    [addButton setTitle:@"添加新司机" forState:UIControlStateNormal];
    [addButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [self.view addSubview:addButton];
    addButton.layer.cornerRadius = 5;
    [addButton addTarget:self action:@selector(addCarDriver) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)createNetWorkAndStatue{
    
    //判断是否有网
    [self judgeNetWork];
    //创建加载状态
}


//判断是否有网
-(void)judgeNetWork{
    if (![RLNetworkHelper isConnectedToNetwork]) {
        [self.tableView addSubview:self.netView];
        self.hud = [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
        
    }
    else{
        [self.netView removeFromSuperview];
        [self initDataSources];
    }
}
//无网络状态
-(void)NoNetPressBtn{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        [self.netView removeFromSuperview];
        [self initDataSources];
    } else {
        [self.hud dismiss:YES];
    }
}


-(void)downRefresh{
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    self.pageNo = 1;
    
    [self judgeNetWork];
}
-(void)upRefresh{
    
    if (self.pageNo != (int)self.pageTotal) {
        self.pageNo ++;
        [self judgeNetWork];
        [self.tableView.mj_footer endRefreshing];
    }else{
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView.mj_header endRefreshing];
}


-(void)addCarDriver
{
    AddCarDriverVC *addVC = [[AddCarDriverVC alloc]init];
    [self.navigationController pushViewController:addVC animated:YES];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    if (self.dataArray.count > 0) {
        
        return self.dataArray.count;

    } else {
        return 0;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = [NSString stringWithFormat:@"mydriverCell"];
    MyDriverCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[MyDriverCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:string];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    if (self.dataArray.count > 0) {
        cell.nameLabel.text = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.section][@"name"]];
        
        cell.phoneLabel.text = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.section][@"phone"]];
        
        
        cell.identifyLabel.text = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.section][@"idNo"]];
        
        
        NSString *str = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.section][@"receiveTime"]];
        
        NSArray *arr = [str componentsSeparatedByString:@" "];
        
        cell.numberLabel.text = arr[0];
        
        cell.styleLabel.text = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.section][@"license"]];
 
    }
    
    
    [cell.deleteButton addTarget:self action:@selector(deleteDriver:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteButton.tag = indexPath.section + 1200;
    
    [cell.editButton addTarget:self action:@selector(editDriver:) forControlEvents:UIControlEventTouchUpInside];
    cell.editButton.tag = indexPath.section + 2200;
    
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = GrayColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 205 * kHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.orderId != nil) {
        
        [self showAlertControllerWithInteger:indexPath.section];

    }
    
    
}

-(void)showAlertControllerWithInteger:(NSInteger)integer
{
    NSString *string = [NSString stringWithFormat:@"此运单是否确定分配给%@",self.dataArray[integer][@"name"]]
    ;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self choiceDriverAndInteger:integer];
        
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

//选择司机并返回上一页面
-(void)choiceDriverAndInteger:(NSInteger)integer
{
    [WKProgressHUD showInView:self.view withText:nil animated:YES];
    
    Common * c = [[Common alloc]init];
    [c afPostRequestWithUrlString:sub_driver_specify parms:@{@"wid":self.orderId,@"uid":self.dataArray[integer][@"id"]} finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        [WKProgressHUD dismissAll:YES];
        
        [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
        
        //延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            if ([dic[@"success"] boolValue]) {
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }
            
        });
    
        
    } failedBlock:^(NSString *errorMsg) {
        
        [WKProgressHUD dismissAll:YES];
        NSLog(@"%@",errorMsg);
    }];
    
}

#pragma mark 删除司机
-(void)deleteDriver:(UIButton *)sender
{
//    NSString *urlString = [NSString stringWithFormat:@"%@sub/deletedriver",Main_interface];
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:sub_deletedriver parms:@{@"dUserId":self.dataArray[sender.tag - 1200][@"did"],@"sUserId":self.dataArray[sender.tag - 1200][@"id"]} finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
        
        if ([dic[@"success"] boolValue]) {
            
            //更新tableview
#warning 可以添加提示框
            [self.dataArray removeObjectAtIndex:sender.tag - 1200];
            
            [self.tableView beginUpdates];
            
            //删除一个section
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sender.tag - 1200] withRowAnimation:UITableViewRowAnimationLeft];
            [self.tableView endUpdates];
            
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self initDataSources];
                
            });

        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

}
#pragma mark 编辑
-(void)editDriver:(UIButton *)sender
{
    
    AddCarDriverVC *addVC = [[AddCarDriverVC alloc]init];
    addVC.license = self.dataArray[sender.tag - 2200][@"license"];
    addVC.name = self.dataArray[sender.tag - 2200][@"name"];
    addVC.phone = self.dataArray[sender.tag - 2200][@"phone"];
    addVC.identify = self.dataArray[sender.tag - 2200][@"idNo"];
    
    NSString *str = [NSString stringWithFormat:@"%@",self.dataArray[sender.tag - 2200][@"receiveTime"]];
    
    NSArray *arr = [str componentsSeparatedByString:@" "];
    
    addVC.recieveDate = arr[0];
    addVC.dUserId = self.dataArray[sender.tag - 2200][@"did"];
    addVC.sUserId = self.dataArray[sender.tag - 2200][@"id"];

    [self.navigationController pushViewController:addVC animated:YES];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
    
    [self initDataSources];
    
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
